﻿using LightingPlatform.TCP;
using LightingPlatform.Tools;
using LightingPlatform.View.Level5;
using LightingPlatform.ViewModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace LightingPlatform.View.Level3
{
    public partial class LightingListView : UserControl, IPageProvider, IExportData
    {
        private ObservableCollection<LightingViewModel> _items = new ObservableCollection<LightingViewModel>();
        private DataPagerProvider _provider = new DataPagerProvider();

        public LightingListView()
        {
            InitializeComponent();

            for (int i = 0; i < 2; i++)
            {
                TitleGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(23) });
            }

            for (int i = 0; i < 11; i++)
            {
                TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(i == 5 ? 220 : 75) });
            }

            TitleGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(85) });

            AddTable(CreateLighting(), 0);
            AddTable(CreateSource(), 6);
            AddTable(CreateOptics(), 10);
            AddTable(CreateBusiness(), 11);

            DataGrid.SelectionChanged += DataGrid_SelectionChanged;
            DataGrid.ItemsSource = _items;
            Loading();
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            LightingViewModel lighting = (LightingViewModel)DataGrid.SelectedItem;
            if (lighting != null)
            {
                LightingContext.Singleton.QueryParameter4 = lighting;
                LightingContext.Singleton.Navigation.Navigate(new Uri("/View/Level4/LightingVersionView.xaml", UriKind.RelativeOrAbsolute));
            }
        }

        private LightingViewModel ConvertForm(Lighting lighting)
        {
            LightingViewModel vm = new LightingViewModel();
            vm.ID = lighting.Id;

            if (lighting.HasPicture && lighting.Picture.HasFacade)
            {
                vm.Picture = new PictureVM();
                vm.Picture.FacadeView = lighting.Picture.Facade;
            }

            if (lighting.HasProject && lighting.Project.HasSetup)
            {
                vm.Project = new ProjectVM();
                vm.Project.Setup = lighting.Project.Setup;
            }

            if (lighting.HasPlace)
                vm.Place = lighting.Place;
            if (lighting.HasSeries)
                vm.Series = lighting.Series;
            if (lighting.HasClass)
                vm.Class = lighting.Class;
            if (lighting.HasVersion)
                vm.Version = lighting.Version;
            if (lighting.HasLable)
                vm.Lable = lighting.Lable;


            if (lighting.HasPhysical && lighting.Physical.HasSize)
            {
                vm.Physical = new PhysicalVM();
                vm.Physical.Size = lighting.Physical.Size;
            }

            if (lighting.HasAdapterLighting)
            {
                vm.AdapterLighting = new AdapterLightingVM();

                if (lighting.AdapterLighting.HasClass)
                    vm.AdapterLighting.Class = lighting.AdapterLighting.Class;
                if (lighting.AdapterLighting.HasColor)
                    vm.AdapterLighting.Color = lighting.AdapterLighting.Color;
                if (lighting.AdapterLighting.HasCri)
                    vm.AdapterLighting.Cri = lighting.AdapterLighting.Cri.ToString();
            }

            if (lighting.HasElectric && lighting.Electric.HasLightingPower)
            {
                vm.Electric = new ElectricVM();
                vm.Electric.LightingPower = lighting.Electric.LightingPower;
            }

            if (lighting.HasOptics && lighting.Optics.HasAngle)
            {
                vm.Optics = new OpticsVM();
                vm.Optics.Angle = lighting.Optics.Angle.ToString();
            }

            if (lighting.HasBusiness && lighting.Business.HasMarket)
            {
                vm.Business = new BusinessVM();
                vm.Business.Market = lighting.Business.Market.ToString();
            }

            return vm;
        }

        public async void Loading()
        {
            busy.IsBusy = true;
            busy.BusyContent = "正在加载数据，请稍等......";
            byte[] response = null;
            if (LightingContext.Singleton.MainPageNavigated)
                response = await TCPClient.Current.Call((int)CommandType.Query, LightingContext.Singleton.QueryParameter.ToByteArray());
            else
                response = await TCPClient.Current.Call((int)CommandType.QueryLevel3, LightingContext.Singleton.QueryParameter3.ToByteArray());
            busy.IsBusy = false;
            if (response == null || response.Length == 0 || response[0] == 0)
            {
                MessageHelper.ShowError("加载数据出错。");
                return;
            }

           
            Lightings lightings = Lightings.ParseFrom(response);
            _items.Clear();
            foreach (Lighting lighting in lightings.LightingList)
            {
                _items.Add(ConvertForm(lighting));
            }
        }

        public async void ExportToExcel()
        {
            if (_items.Count == 0)
                return;

            busy.IsBusy = true;
            busy.BusyContent = "正在导出数据，请稍等......";
            byte[] response = null;
            if (LightingContext.Singleton.MainPageNavigated)
                response = await TCPClient.Current.Call((int)CommandType.QueryExportExcel, LightingContext.Singleton.QueryParameter.ToByteArray());
            else
                response = await TCPClient.Current.Call((int)CommandType.QueryLevel3ExportExcel, LightingContext.Singleton.QueryParameter3.ToByteArray());
            busy.IsBusy = false;
            if (response == null || response.Length == 0 || response[0] == 0)
            {
                MessageHelper.ShowError("导出数据出错。");
                return;
            }

            string url = Encoding.UTF8.GetString(response, 0, response.Length);
            HtmlPage.Window.Navigate(new Uri(url));
        }

        public async void ExportToPdf()
        {
            if (_items.Count == 0)
                return;

            busy.IsBusy = true;
            busy.BusyContent = "正在导出数据，请稍等......";
            byte[] response = null;
            if (LightingContext.Singleton.MainPageNavigated)
                response = await TCPClient.Current.Call((int)CommandType.QueryExportPdf, LightingContext.Singleton.QueryParameter.ToByteArray());
            else
                response = await TCPClient.Current.Call((int)CommandType.QueryLevel3ExportPdf, LightingContext.Singleton.QueryParameter3.ToByteArray());
            busy.IsBusy = false;
            if (response == null || response.Length == 0 || response[0] == 0)
            {
                MessageHelper.ShowError("加载数据出错");
                return;
            }

            string url = Encoding.UTF8.GetString(response, 0, response.Length);
            HtmlPage.Window.Navigate(new Uri(url));
        }

        private void AddTable(LightingTable table, int columnIndex)
        {
            SolidColorBrush brush = new SolidColorBrush(table.Backgroud);

            Grid tableTitle = CreateTitleCell(table.Name, 0, columnIndex, 14);
            tableTitle.Background = brush;
            TitleGrid.Children.Add(tableTitle);
            Grid.SetColumn(tableTitle, columnIndex);
            Grid.SetColumnSpan(tableTitle, table.Columns.Length);

            int startColumnIndex = 0;
            foreach (ColumnProperty column in table.Columns)
            {
                Grid columnTitle = CreateTitleCell(column.Name, 1, startColumnIndex + columnIndex);
                columnTitle.Background = brush;
                TitleGrid.Children.Add(columnTitle);
                Grid.SetRow(columnTitle, 1);
                Grid.SetColumn(columnTitle, startColumnIndex + columnIndex);

                startColumnIndex++;
            }
        }

        private Grid CreateTitleCell(string text, int rowIndex, int columIndex, double fontsize = 13)
        {
            Grid grid = new Grid();

            Border border = new Border();
            border.BorderBrush = new SolidColorBrush(Colors.White);

            if (rowIndex == 0)
            {
                if (columIndex > 0)
                {
                    border.BorderThickness = new Thickness(1, 0, 0, 0);
                }
                else
                {
                    border.BorderThickness = new Thickness(0);
                }
            }
            else
            {
                if (columIndex == 0)
                {
                    border.BorderThickness = new Thickness(0, 1, 0, 0);
                }
                else
                {
                    border.BorderThickness = new Thickness(1, 1, 0, 0);
                }
            }

            grid.Children.Add(border);

            TextBlock tb = new TextBlock();
            tb.Text = text;
            tb.FontSize = fontsize;
            tb.HorizontalAlignment = HorizontalAlignment.Center;
            tb.VerticalAlignment = VerticalAlignment.Center;

            grid.Children.Add(tb);
            return grid;
        }

        public LightingTable CreateLighting()
        {
            return new LightingTable()
            {
                Name = "产品描述",
                Columns = new ColumnProperty[]
                {
                    new ColumnProperty { Name = "产品图片" },
                    new ColumnProperty { Name = "产品系列" },
                    new ColumnProperty { Name = "产品分类" },
                    new ColumnProperty { Name = "规格型号" },
                    new ColumnProperty { Name = "产品品牌" },
                    new ColumnProperty { Name = "外形尺寸" },
                },
                Backgroud = Color.FromArgb(255, 234, 234, 234),
            };
        }

        public LightingTable CreateSource()
        {
            return new LightingTable()
            {
                Name = "光源描述",
                Columns = new ColumnProperty[]
                {
                    new ColumnProperty { Name = "光源种类" },
                    new ColumnProperty { Name = "光源功率" },
                    new ColumnProperty { Name = "光学色温" },
                    new ColumnProperty { Name = "显色性" },
                },
                Backgroud = Color.FromArgb(255, 204, 204, 204),
            };
        }

        public LightingTable CreateOptics()
        {
            return new LightingTable()
            {
                Name = "光学参数",
                Columns = new ColumnProperty[]
                {
                    new ColumnProperty { Name = "光束角" },
                },
                Backgroud = Color.FromArgb(255, 234, 234, 234)

            };
        }

        public LightingTable CreateBusiness()
        {
            return new LightingTable()
            {
                Name = "商务参数",
                Columns = new ColumnProperty[]
                {
                    new ColumnProperty { Name = "市场参考价"},
                },
                Backgroud = Color.FromArgb(255, 204, 204, 204)
            };
        }

        public PageLevel PageLevel
        {
            get { return PageLevel.Third; }
        }
    }
}
